package com.situ.mall.base.service.impl;

import com.situ.mall.base.entity.Attachment;
import com.situ.mall.base.mapper.AttachmentMapper;
import com.situ.mall.base.service.IAttachmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.base.util.C;
import com.situ.mall.base.util.FileUtil;
import com.situ.mall.base.vo.ResVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author darling
 * @since 2023-03-21
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {

    @Override
    public List<Attachment> getList(Integer sourceId, String source) {
        return baseMapper.getList(sourceId, source);
    }

    @Override
    public void updateSource(String ids, Integer pId) {
        for (String id: ids.split(",")) {
            baseMapper.updateSelect(Integer.valueOf(id), pId);
        }
    }


    @Override
    public synchronized ResVO upload(MultipartFile file) {
        ResVO vo = new ResVO();
        String fileName = System.currentTimeMillis() + C.PNG;
        File f = new File(C.PRODUCT_PATH, fileName);
        try {
            file.transferTo(f);
        } catch (Exception e) {
            vo.setCode(1);
            throw new RuntimeException(e);
        }
        Attachment attachment = new Attachment();
        attachment.setSource("product");
        attachment.setPath(fileName);
        attachment.setCreatetime(LocalDateTime.now());
        attachment.setFileName(file.getOriginalFilename());
        attachment.setFileSize(FileUtil.formatFileSize(file.getSize()));
        attachment.setType(file.getContentType());
        baseMapper.insert(attachment);
        Map<String, Integer> map = new HashMap<>();
        map.put(C.ID, attachment.getId());
        vo.setData(map);
        return vo;
    }

    @Override
    public List<Attachment> getBySourceAndSourceId(String source, Integer sourceId) {
        return baseMapper.getBySourceAndSourceId(source, sourceId);
    }


}
